<!DOCTYPE html><html lang="zh-CN" data-theme="dark"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"><title>Golang日志管理 | J.のblog</title><meta name="keywords" content="云原生,golang"><meta name="author" content="J."><meta name="copyright" content="J."><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#0d0d0d"><meta name="description" content="日志标准库的log包Go标准库中有log包，提供了简单的日志功能。    输出 格式输出 换行输出     log.Print() log.Printf() log.Pringln() 类似fmt.print*   log.Fatal() log.Fatalf() log.Fatalln() 相当于log.Print* + os.Exit(1)   log.Panic() log.Panicf()">
<meta property="og:type" content="article">
<meta property="og:title" content="Golang日志管理">
<meta property="og:url" content="http://dycloudnavite.love/2023/05/01/Golang%E6%97%A5%E5%BF%97%E7%AE%A1%E7%90%86/index.html">
<meta property="og:site_name" content="J.のblog">
<meta property="og:description" content="日志标准库的log包Go标准库中有log包，提供了简单的日志功能。    输出 格式输出 换行输出     log.Print() log.Printf() log.Pringln() 类似fmt.print*   log.Fatal() log.Fatalf() log.Fatalln() 相当于log.Print* + os.Exit(1)   log.Panic() log.Panicf()">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="http://dycloudnavite.love/img/golang.png">
<meta property="article:published_time" content="2023-05-01T06:32:00.000Z">
<meta property="article:modified_time" content="2023-08-30T02:59:55.081Z">
<meta property="article:author" content="J.">
<meta property="article:tag" content="云原生">
<meta property="article:tag" content="golang">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://dycloudnavite.love/img/golang.png"><link rel="shortcut icon" href="/dujie5416/img/touxiang.png"><link rel="canonical" href="http://dycloudnavite.love/2023/05/01/Golang%E6%97%A5%E5%BF%97%E7%AE%A1%E7%90%86/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/dujie5416/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/dujie5416/',
  algolia: {"appId":"9GWB2VV7GN","apiKey":"dac56ec5b0b1f45281251ee59db4d637","indexName":"blog","hits":{"per_page":6},"languages":{"input_placeholder":"搜索文章","hits_empty":"找不到您查询的内容：${query}","hits_stats":"找到 ${hits} 条结果，用时 ${time} 毫秒"}},
  localSearch: undefined,
  translate: {"defaultEncoding":2,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"簡"},
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isAnchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'Golang日志管理',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2023-08-30 10:59:55'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><link rel="stylesheet" href="/xxx.css"><link rel="stylesheet" href="/css/universe.css"><link rel="stylesheet" href="/css/custom.css"><style type="text/css">#toggle-sidebar {bottom: 80px}</style><link rel="stylesheet" href="https://fastly.jsdelivr.net/gh/tzy13755126023/BLOG_SOURCE/css/function.min.css"><link rel="stylesheet" href="/css/rightMenu.css"><style type="text/css">#toggle-sidebar {left:100px}</style><!-- hexo injector head_end start --><link rel="stylesheet" href="https://cdn.cbd.int/hexo-butterfly-clock-anzhiyu/lib/clock.min.css" /><!-- hexo injector head_end end --><meta name="generator" content="Hexo 6.2.0"><link rel="alternate" href="/dujie5416/atom.xml" title="J.のblog" type="application/atom+xml">
</head><body><div id="loading-box"><div class="loading-left-bg"></div><div class="loading-right-bg"></div><div class="spinner-box"><div class="configure-border-1"><div class="configure-core"></div></div><div class="configure-border-2"><div class="configure-core"></div></div><div class="loading-word">加载中...</div></div></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="/dujie5416/img/touxiang.png" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/dujie5416/archives/"><div class="headline">文章</div><div class="length-num">73</div></a><a href="/dujie5416/tags/"><div class="headline">标签</div><div class="length-num">17</div></a><a href="/dujie5416/categories/"><div class="headline">分类</div><div class="length-num">11</div></a></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/dujie5416/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/dujie5416/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/dujie5416/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/dujie5416/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('/dujie5416/img/longzhu.png')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/dujie5416/">J.のblog</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/dujie5416/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/dujie5416/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/dujie5416/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/dujie5416/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">Golang日志管理</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2023-05-01T06:32:00.000Z" title="发表于 2023-05-01 14:32:00">2023-05-01</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2023-08-30T02:59:55.081Z" title="更新于 2023-08-30 10:59:55">2023-08-30</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/dujie5416/categories/golang/">golang</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="Golang日志管理"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h1 id="日志"><a href="#日志" class="headerlink" title="日志"></a>日志</h1><h3 id="标准库的log包"><a href="#标准库的log包" class="headerlink" title="标准库的log包"></a><strong>标准库的log包</strong></h3><p>Go标准库中有log包，提供了简单的日志功能。</p>
<table>
<thead>
<tr>
<th><strong>输出</strong></th>
<th><strong>格式输出</strong></th>
<th><strong>换行输出</strong></th>
<th></th>
</tr>
</thead>
<tbody><tr>
<td>log.Print()</td>
<td>log.Printf()</td>
<td>log.Pringln()</td>
<td>类似fmt.print*</td>
</tr>
<tr>
<td>log.Fatal()</td>
<td>log.Fatalf()</td>
<td>log.Fatalln()</td>
<td>相当于log.Print* + os.Exit(1)</td>
</tr>
<tr>
<td>log.Panic()</td>
<td>log.Panicf()</td>
<td>log.Panicln()</td>
<td>相当于log.Print* + panic(0</td>
</tr>
</tbody></table>
<p>日志输出需要使用日志记录器Logger。</p>
<p>log包提供了一个缺省的Logger即std。std是小写的，包外不可见，所以提供了Default()方法返回std给包外使用。如下：</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">package</span> main

<span class="token keyword">import</span> <span class="token punctuation">(</span>
	<span class="token string">"log"</span>
<span class="token punctuation">)</span>

<span class="token keyword">func</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token comment">// 这里就是使用缺省的logger对象，可以点进Println查看源码</span>
	log<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"这是缺省的logger"</span><span class="token punctuation">)</span>
<span class="token punctuation">&#125;</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>源码如下：</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token comment">// go源码</span>
<span class="token comment">// Println calls Output to print to the standard logger.</span>
<span class="token comment">// Arguments are handled in the manner of fmt.Println.</span>
<span class="token keyword">func</span> <span class="token function">Println</span><span class="token punctuation">(</span>v <span class="token operator">...</span>any<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
	<span class="token keyword">if</span> std<span class="token punctuation">.</span>isDiscard<span class="token punctuation">.</span><span class="token function">Load</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
		<span class="token keyword">return</span>
	<span class="token punctuation">&#125;</span>
	std<span class="token punctuation">.</span><span class="token function">Output</span><span class="token punctuation">(</span><span class="token number">2</span><span class="token punctuation">,</span> fmt<span class="token punctuation">.</span><span class="token function">Sprintln</span><span class="token punctuation">(</span>v<span class="token operator">...</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
<span class="token punctuation">&#125;</span>
<span class="token comment">// 再点击std可以查看到，这里有一个默认的std，他的输出是os.Stderr标准错误输出到控制台，flag为LstdFlags</span>
<span class="token keyword">var</span> std <span class="token operator">=</span> <span class="token function">New</span><span class="token punctuation">(</span>os<span class="token punctuation">.</span>Stderr<span class="token punctuation">,</span> <span class="token string">""</span><span class="token punctuation">,</span> LstdFlags<span class="token punctuation">)</span>

<span class="token comment">// Default returns the standard logger used by the package-level output functions.</span>
<span class="token keyword">func</span> <span class="token function">Default</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">*</span>Logger <span class="token punctuation">&#123;</span> <span class="token keyword">return</span> std <span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>标准库的flag如下：</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token comment">// 源码41行左右</span>
<span class="token comment">//	2009/01/23 01:23:23.123123 /a/b/c/d.go:23: message</span>
<span class="token keyword">const</span> <span class="token punctuation">(</span>
	Ldate         <span class="token operator">=</span> <span class="token number">1</span> <span class="token operator">&lt;&lt;</span> <span class="token boolean">iota</span>     <span class="token comment">// 1 当前时区日期: 2009/01/23</span>
	Ltime                         <span class="token comment">// 2 当前时区时间: 01:23:23</span>
	Lmicroseconds                 <span class="token comment">// 4 微秒: 01:23:23.123123.  assumes Ltime.</span>
	Llongfile                     <span class="token comment">// 8 绝对路径和行号: /a/b/c/d.go:23</span>
	Lshortfile                    <span class="token comment">// 16 文件名和行号: d.go:23. overrides Llongfile</span>
	LUTC                          <span class="token comment">// 32 使用UTC(GMT)，而不是本地时区</span>
	Lmsgprefix                    <span class="token comment">// 64 默认前缀是放在行首的，这个标记为把前缀prefix放到消息message之前</span>
	LstdFlags     <span class="token operator">=</span> Ldate <span class="token operator">|</span> Ltime <span class="token comment">// 3 initial values for the standard logger  位或，二进制的01 | 10 = 11 =》十进制3</span>
<span class="token punctuation">)</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>上表列出的方法底层都使用std.Output输出日志内容。而std本质上是使用了<strong>标准错误输出</strong>、<strong>无前缀</strong>、<strong>LstdFlags 标准标记</strong>的记录器Logger实例</p>
<h5 id="std使用"><a href="#std使用" class="headerlink" title="std使用"></a><strong>std使用</strong></h5><pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token comment">// 使用缺省Logger</span>
log<span class="token punctuation">.</span><span class="token function">Print</span><span class="token punctuation">(</span><span class="token string">"abcde\n"</span><span class="token punctuation">)</span>
log<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">"%s\n"</span><span class="token punctuation">,</span><span class="token string">"abcd"</span><span class="token punctuation">)</span>
log<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"abcd"</span><span class="token punctuation">)</span>

log<span class="token punctuation">.</span><span class="token function">Fatal</span><span class="token punctuation">(</span><span class="token string">"xyz"</span><span class="token punctuation">)</span> <span class="token comment">// 等价于 log.Print("xyz");os.Exit(1)</span>

log<span class="token punctuation">.</span><span class="token function">Panic</span><span class="token punctuation">(</span><span class="token string">"xyz"</span><span class="token punctuation">)</span> <span class="token comment">// 等价于 log.Print("xyz");panic()</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>




<h5 id="自定义Logger"><a href="#自定义Logger" class="headerlink" title="自定义Logger"></a><strong>自定义Logger</strong></h5><p>Go源码</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token comment">// multiple goroutines; it guarantees to serialize access to the Writer.</span>
<span class="token keyword">type</span> Logger <span class="token keyword">struct</span> <span class="token punctuation">&#123;</span>
	mu        sync<span class="token punctuation">.</span>Mutex  <span class="token comment">// ensures atomic writes; protects the following fields</span>
	prefix    <span class="token builtin">string</span>      <span class="token comment">// prefix on each line to identify the logger (but see Lmsgprefix)</span>
	flag      <span class="token builtin">int</span>         <span class="token comment">// properties</span>
	out       io<span class="token punctuation">.</span>Writer   <span class="token comment">// destination for output</span>
	buf       <span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token builtin">byte</span>      <span class="token comment">// for accumulating text to write</span>
	isDiscard atomic<span class="token punctuation">.</span>Bool <span class="token comment">// whether out == io.Discard</span>
<span class="token punctuation">&#125;</span>

<span class="token comment">// New creates a new Logger. The out variable sets the</span>
<span class="token comment">// destination to which log data will be written.</span>
<span class="token comment">// The prefix appears at the beginning of each generated log line, or</span>
<span class="token comment">// after the log header if the Lmsgprefix flag is provided.</span>
<span class="token comment">// The flag argument defines the logging properties.</span>
<span class="token keyword">func</span> <span class="token function">New</span><span class="token punctuation">(</span>out io<span class="token punctuation">.</span>Writer<span class="token punctuation">,</span> prefix <span class="token builtin">string</span><span class="token punctuation">,</span> flag <span class="token builtin">int</span><span class="token punctuation">)</span> <span class="token operator">*</span>Logger <span class="token punctuation">&#123;</span>
	l <span class="token operator">:=</span> <span class="token operator">&amp;</span>Logger<span class="token punctuation">&#123;</span>out<span class="token punctuation">:</span> out<span class="token punctuation">,</span> prefix<span class="token punctuation">:</span> prefix<span class="token punctuation">,</span> flag<span class="token punctuation">:</span> flag<span class="token punctuation">&#125;</span>
	<span class="token keyword">if</span> out <span class="token operator">==</span> io<span class="token punctuation">.</span>Discard <span class="token punctuation">&#123;</span>
		l<span class="token punctuation">.</span>isDiscard<span class="token punctuation">.</span><span class="token function">Store</span><span class="token punctuation">(</span><span class="token boolean">true</span><span class="token punctuation">)</span>
	<span class="token punctuation">&#125;</span>
	<span class="token keyword">return</span> l
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>如果觉得缺省Logger std不满意，可以New构建一个自定义Logger并指定前缀、Flags。</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">package</span> main

<span class="token keyword">import</span> <span class="token punctuation">(</span>
	<span class="token string">"log"</span>
	<span class="token string">"os"</span>
<span class="token punctuation">)</span>

<span class="token keyword">func</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
	log<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"这是缺省的logger"</span><span class="token punctuation">)</span>

        
	infologger <span class="token operator">:=</span> log<span class="token punctuation">.</span><span class="token function">New</span><span class="token punctuation">(</span>os<span class="token punctuation">.</span>Stderr<span class="token punctuation">,</span> <span class="token string">"Info："</span><span class="token punctuation">,</span> <span class="token number">3</span><span class="token operator">|</span>log<span class="token punctuation">.</span>Lmsgprefix<span class="token punctuation">)</span>
	infologger<span class="token punctuation">.</span><span class="token function">Print</span><span class="token punctuation">(</span><span class="token string">"这是自定义的普通消息"</span><span class="token punctuation">)</span>

	errLogger <span class="token operator">:=</span> log<span class="token punctuation">.</span><span class="token function">New</span><span class="token punctuation">(</span>os<span class="token punctuation">.</span>Stderr<span class="token punctuation">,</span> <span class="token string">"Error:"</span><span class="token punctuation">,</span> log<span class="token punctuation">.</span>LstdFlags<span class="token punctuation">)</span>
	errLogger<span class="token punctuation">.</span><span class="token function">Fatalln</span><span class="token punctuation">(</span><span class="token string">"这是一个自定义的错误消息"</span><span class="token punctuation">)</span>

<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>


<p><strong>log.New 参数详解：</strong></p>
<ul>
<li>1、<code>out io.Writer</code> ：er结尾说明是一个接口，out应该有自己的类型，同时其类型又实现了Writer的所有方法，所以out也可以看做为io.Writer类型的实例，out主要用于写入设备</li>
<li>2、<code>prefix string</code> ：前缀，用于在日志前面增加一串字符串，可以通过flag参数设置为<code>log.Lmsgprefix</code>将它设置为在message前面</li>
<li>3、<code>flag int</code> ：确定Logger的工作方式如下：</li>
</ul>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token comment">// 源码41行左右</span>
<span class="token comment">//	2009/01/23 01:23:23.123123 /a/b/c/d.go:23: message</span>
<span class="token keyword">const</span> <span class="token punctuation">(</span>  <span class="token comment">// 可以做位与、为或</span>
	Ldate         <span class="token operator">=</span> <span class="token number">1</span> <span class="token operator">&lt;&lt;</span> <span class="token boolean">iota</span>     <span class="token comment">// 1 当前时区日期: 2009/01/23</span>
	Ltime                         <span class="token comment">// 2 当前时区时间: 01:23:23</span>
	Lmicroseconds                 <span class="token comment">// 4 微秒: 01:23:23.123123.  assumes Ltime.</span>
	Llongfile                     <span class="token comment">// 8 绝对路径和行号: /a/b/c/d.go:23</span>
	Lshortfile                    <span class="token comment">// 16 文件名和行号: d.go:23. overrides Llongfile</span>
	LUTC                          <span class="token comment">// 32 使用UTC(GMT)，而不是本地时区</span>
	Lmsgprefix                    <span class="token comment">// 64 默认前缀是放在行首的，这个标记为把前缀prefix放到消息message之前</span>
	LstdFlags     <span class="token operator">=</span> Ldate <span class="token operator">|</span> Ltime <span class="token comment">// 3 initial values for the standard logger  位或，二进制的01 | 10 = 11 =》十进制3</span>
<span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p><img src="/images/BDP-9YI67K64UgUIaM4LFXWCdmzzRjGhBWuxyga9jSo.png" alt="image"></p>
<h5 id="写日志文件"><a href="#写日志文件" class="headerlink" title="写日志文件"></a><strong>写日志文件</strong></h5><p>New方法签名<code>func New(out io.Writer, prefix string, flag int) *Logger</code> 中out参数提供Writer接口即可，那么就可以提供一个可写文件对象</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">package</span> main

<span class="token keyword">import</span> <span class="token punctuation">(</span>
	<span class="token string">"fmt"</span>
	<span class="token string">"log"</span>
	<span class="token string">"os"</span>
<span class="token punctuation">)</span>

<span class="token keyword">func</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
         <span class="token comment">// os.Open为只读打开，OpenFile按照指定方式打开文件</span>
	file<span class="token punctuation">,</span> err <span class="token operator">:=</span> os<span class="token punctuation">.</span><span class="token function">OpenFile</span><span class="token punctuation">(</span><span class="token string">"C:\\Users\\Administrator\\Desktop\\test.txt"</span><span class="token punctuation">,</span>
         os<span class="token punctuation">.</span>O_APPEND<span class="token operator">|</span>os<span class="token punctuation">.</span>O_WRONLY<span class="token punctuation">,</span> <span class="token comment">// 追加| 只写</span>
         <span class="token number">777</span><span class="token punctuation">)</span>  <span class="token comment">// 权限为777</span>
	<span class="token keyword">if</span> err <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token punctuation">&#123;</span>
		fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>err<span class="token punctuation">)</span>
	<span class="token punctuation">&#125;</span>
        <span class="token keyword">defer</span> file<span class="token punctuation">.</span><span class="token function">Close</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token comment">// 使用结束关闭文件句柄</span>
	logger <span class="token operator">:=</span> log<span class="token punctuation">.</span><span class="token function">New</span><span class="token punctuation">(</span>file<span class="token punctuation">,</span> <span class="token string">"Info："</span><span class="token punctuation">,</span> <span class="token number">3</span><span class="token punctuation">)</span>
	logger<span class="token punctuation">.</span><span class="token function">Print</span><span class="token punctuation">(</span><span class="token string">"这是一条测试的日志"</span><span class="token punctuation">)</span>

<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>


<h3 id="ZeroLog"><a href="#ZeroLog" class="headerlink" title="ZeroLog"></a><strong>ZeroLog</strong></h3><p>log模块太简陋了，实际使用并不方便。</p>
<ul>
<li>logrus有日志级别、Hook机制、日志输出格式，很好用</li>
<li>zap是Uber的开源高性能日志库</li>
<li>zerolog更注重开发体验，高性能、有日志级别、链式API，json格式记录，号称0内存分配</li>
</ul>
<p>官网： <a target="_blank" rel="noopener" href="https://zerolog.io/">https://zerolog.io/</a></p>
<p>安装 </p>
<pre class="line-numbers language-Plain" data-language="Plain"><div class="caption"><span>Text</span></div><code class="language-Plain">go get -u github.com&#x2F;rs&#x2F;zerolog&#x2F;log<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<h5 id="缺省Logger"><a href="#缺省Logger" class="headerlink" title="缺省Logger"></a><strong>缺省Logger</strong></h5><pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">package</span> main

<span class="token keyword">import</span> <span class="token punctuation">(</span>
	<span class="token string">"github.com/rs/zerolog"</span>
	<span class="token string">"github.com/rs/zerolog/log"</span>
	<span class="token string">"os"</span>
	<span class="token string">"time"</span>
<span class="token punctuation">)</span>

<span class="token keyword">func</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>

	zerolog<span class="token punctuation">.</span>TimeFieldFormat <span class="token operator">=</span> <span class="token string">"2006/01/02 15:04:05 -0700"</span>
	log<span class="token punctuation">.</span><span class="token function">Print</span><span class="token punctuation">(</span><span class="token string">"这是zerolog的默认消息"</span><span class="token punctuation">)</span> <span class="token comment">// 使用全局缺省logger</span>
	<span class="token comment">// 输出&#123;"level":"debug","time":"2023/07/23 13:55:05 +0800","message":"这是zerolog的默认消息"&#125;</span>
       
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>log.Print 产生debug级别的消息，zerolog源码117行左右</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token comment">// Print sends a log event using debug level and no extra field.</span>
<span class="token comment">// Arguments are handled in the manner of fmt.Print.</span>
<span class="token keyword">func</span> <span class="token function">Print</span><span class="token punctuation">(</span>v <span class="token operator">...</span><span class="token keyword">interface</span><span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
	Logger<span class="token punctuation">.</span><span class="token function">Debug</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">CallerSkipFrame</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Msg</span><span class="token punctuation">(</span>fmt<span class="token punctuation">.</span><span class="token function">Sprint</span><span class="token punctuation">(</span>v<span class="token operator">...</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
<span class="token punctuation">&#125;</span>

<span class="token comment">// 源码13行左右，定义了一个全局导出的缺省Logger，使用链式调用，缺省Logger使用标准错误输出</span>
<span class="token keyword">var</span> Logger <span class="token operator">=</span> zerolog<span class="token punctuation">.</span><span class="token function">New</span><span class="token punctuation">(</span>os<span class="token punctuation">.</span>Stderr<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">With</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Timestamp</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Logger</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>log.Print()、log.Printf()方法使用方式和标准库log模块类似</p>
<h5 id="级别"><a href="#级别" class="headerlink" title="级别"></a><strong>级别</strong></h5><p>zerolog提供以下级别，tracelevel级别最低-1</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token comment">// zerolog源码112行</span>
<span class="token keyword">type</span> Level <span class="token builtin">int8</span>

<span class="token keyword">const</span> <span class="token punctuation">(</span>
	<span class="token comment">// DebugLevel defines debug log level.</span>
	DebugLevel Level <span class="token operator">=</span> <span class="token boolean">iota</span>     <span class="token number">0</span>
	<span class="token comment">// InfoLevel defines info log level.</span>
	InfoLevel    <span class="token number">1</span>
	<span class="token comment">// WarnLevel defines warn log level.</span>
	WarnLevel    <span class="token number">2</span>
	<span class="token comment">// ErrorLevel defines error log level.</span>
	ErrorLevel   <span class="token number">3</span>
	<span class="token comment">// FatalLevel defines fatal log level.</span>
	FatalLevel   <span class="token number">4</span>
	<span class="token comment">// PanicLevel defines panic log level.</span>
	PanicLevel   <span class="token number">5</span>
	<span class="token comment">// NoLevel defines an absent log level.</span>
	NoLevel      <span class="token number">6</span>
	<span class="token comment">// Disabled disables the logger.</span>
	Disabled     <span class="token number">7</span>

	<span class="token comment">// TraceLevel defines trace log level.</span>
	TraceLevel Level <span class="token operator">=</span> <span class="token operator">-</span><span class="token number">1</span>
	<span class="token comment">// Values less than TraceLevel are handled as numbers.</span>
<span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>


<p>级别有</p>
<ul>
<li>gLevel全局级别<ul>
<li><code>zerolog.SetGlobalLevel(级别数字或常量)</code> 来设置全局级别</li>
<li><code>zerolog.GlobalLevel()</code> 获取当前全局级别</li>
</ul>
</li>
<li>每个Logger的级别</li>
<li>消息的级别</li>
</ul>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">package</span> main

<span class="token keyword">import</span> <span class="token punctuation">(</span>
	<span class="token string">"fmt"</span>
	<span class="token string">"github.com/rs/zerolog"</span>
	<span class="token string">"github.com/rs/zerolog/log"</span>
<span class="token punctuation">)</span>

<span class="token keyword">func</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
	fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"全局级别的glevel为："</span><span class="token punctuation">,</span> zerolog<span class="token punctuation">.</span><span class="token function">GlobalLevel</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
	fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"缺省logger的级别为："</span><span class="token punctuation">,</span> log<span class="token punctuation">.</span>Logger<span class="token punctuation">.</span><span class="token function">GetLevel</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
	log1 <span class="token operator">:=</span> log<span class="token punctuation">.</span><span class="token function">Level</span><span class="token punctuation">(</span>zerolog<span class="token punctuation">.</span>WarnLevel<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">With</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Logger</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
	fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"log1的级别为"</span><span class="token punctuation">,</span> log1<span class="token punctuation">.</span><span class="token function">GetLevel</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>

	fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"~~~~~~~~~~~~~~~~"</span><span class="token punctuation">)</span>
	log<span class="token punctuation">.</span><span class="token function">Trace</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Msg</span><span class="token punctuation">(</span><span class="token string">"缺省logger输出trace级别消息"</span><span class="token punctuation">)</span> <span class="token comment">// 可以输出</span>
	log<span class="token punctuation">.</span><span class="token function">Info</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Msg</span><span class="token punctuation">(</span><span class="token string">"缺省logger输出info级别消息"</span><span class="token punctuation">)</span> <span class="token comment">// 可以输出</span>
	log<span class="token punctuation">.</span><span class="token function">Warn</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Msg</span><span class="token punctuation">(</span><span class="token string">"缺省logger输出warn级别消息"</span><span class="token punctuation">)</span> <span class="token comment">// 可以输出</span>
	log<span class="token punctuation">.</span><span class="token function">Error</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Msg</span><span class="token punctuation">(</span><span class="token string">"缺省logger输出error级别消息"</span><span class="token punctuation">)</span> <span class="token comment">// 可以输出</span>
	<span class="token comment">//log.Fatal().Msg("缺省logger输出fatal级别消息") </span>
	<span class="token comment">//log.Panic().Msg("缺省logger输出panic级别消息")</span>
	
	log1<span class="token punctuation">.</span><span class="token function">Debug</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Msg</span><span class="token punctuation">(</span><span class="token string">"log1输出debug级别消息"</span><span class="token punctuation">)</span> <span class="token comment">// 输出不了，因为log1的消息级别为debug，小于log1的级别warn</span>
	log1<span class="token punctuation">.</span><span class="token function">Error</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Msg</span><span class="token punctuation">(</span><span class="token string">"log1输出error级别消息"</span><span class="token punctuation">)</span> <span class="token comment">// 可以输出，因为log1的消息级别为error，大于log1的级别warn</span>
<span class="token punctuation">&#125;</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>可以看到，使用缺省logger，全部可以输出日志消息，而log1的24行可以输出，23行不能输出，<strong>因为有消息级别和Logger级别</strong></p>
<p>log1的级别为warn，而log1.Debug()输出的消息级别为debug级别0，消息级别小于log1级别，所以消息不能输出。log1.Error()产生error消息，消息级别 大于等于log1级别的warn，因此可以输出消息。</p>
<p>而缺省的Logger级别为trace，任何消息级别都大于等于缺省的logger的级别，因此都可以输出</p>
<p>下面可以调整全局级别看一看</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">package</span> main

<span class="token keyword">import</span> <span class="token punctuation">(</span>
	<span class="token string">"fmt"</span>
	<span class="token string">"github.com/rs/zerolog"</span>
	<span class="token string">"github.com/rs/zerolog/log"</span>
<span class="token punctuation">)</span>

<span class="token keyword">func</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
	zerolog<span class="token punctuation">.</span><span class="token function">SetGlobalLevel</span><span class="token punctuation">(</span>zerolog<span class="token punctuation">.</span>ErrorLevel<span class="token punctuation">)</span>
	fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"全局级别的glevel为："</span><span class="token punctuation">,</span> zerolog<span class="token punctuation">.</span><span class="token function">GlobalLevel</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>

	fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"缺省logger的级别为："</span><span class="token punctuation">,</span> log<span class="token punctuation">.</span>Logger<span class="token punctuation">.</span><span class="token function">GetLevel</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
	log1 <span class="token operator">:=</span> log<span class="token punctuation">.</span><span class="token function">Level</span><span class="token punctuation">(</span>zerolog<span class="token punctuation">.</span>WarnLevel<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">With</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Logger</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token comment">// 创建一个子logger</span>
	fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"log1的级别为"</span><span class="token punctuation">,</span> log1<span class="token punctuation">.</span><span class="token function">GetLevel</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>

	fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"~~~~~~~~~~~~~~~~"</span><span class="token punctuation">)</span>
	log<span class="token punctuation">.</span><span class="token function">Trace</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Msg</span><span class="token punctuation">(</span><span class="token string">"缺省logger输出trace级别消息"</span><span class="token punctuation">)</span> <span class="token comment">// 不能输出</span>
	log<span class="token punctuation">.</span><span class="token function">Info</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Msg</span><span class="token punctuation">(</span><span class="token string">"缺省logger输出info级别消息"</span><span class="token punctuation">)</span>   <span class="token comment">// 不能输出</span>
	log<span class="token punctuation">.</span><span class="token function">Warn</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Msg</span><span class="token punctuation">(</span><span class="token string">"缺省logger输出warn级别消息"</span><span class="token punctuation">)</span>   <span class="token comment">// 不能输出</span>
	log<span class="token punctuation">.</span><span class="token function">Error</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Msg</span><span class="token punctuation">(</span><span class="token string">"缺省logger输出error级别消息"</span><span class="token punctuation">)</span> <span class="token comment">// 可以输出</span>
	<span class="token comment">//log.Fatal().Msg("缺省logger输出fatal级别消息")</span>
	<span class="token comment">//log.Panic().Msg("缺省logger输出panic级别消息")</span>

	log1<span class="token punctuation">.</span><span class="token function">Warn</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Msg</span><span class="token punctuation">(</span><span class="token string">"log1输出warn级别消息"</span><span class="token punctuation">)</span> <span class="token comment">// 输出不了，因为log1的消息级别为debug，虽然等于log1的级别warn，但是小于全局的glevel的error级别，所以还是输出不了</span>
	log1<span class="token punctuation">.</span><span class="token function">Error</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Msg</span><span class="token punctuation">(</span><span class="token string">"log1输出error级别消息"</span><span class="token punctuation">)</span> <span class="token comment">// 可以输出，因为log1的消息级别为error，大于log1的级别warn，且等于全局的glevel的error级别，所以可以输出</span>
<span class="token punctuation">&#125;</span>
<span class="token comment">// 输出</span>
全局级别的glevel为： <span class="token builtin">error</span>
缺省logger的级别为： trace
log1的级别为 warn
~~~~~~~~~~~~~~~~
<span class="token punctuation">&#123;</span><span class="token string">"level"</span><span class="token punctuation">:</span><span class="token string">"error"</span><span class="token punctuation">,</span><span class="token string">"time"</span><span class="token punctuation">:</span><span class="token string">"2023-07-23T14:22:39+08:00"</span><span class="token punctuation">,</span><span class="token string">"message"</span><span class="token punctuation">:</span><span class="token string">"缺省logger输出error级别消息"</span><span class="token punctuation">&#125;</span>
<span class="token punctuation">&#123;</span><span class="token string">"level"</span><span class="token punctuation">:</span><span class="token string">"error"</span><span class="token punctuation">,</span><span class="token string">"time"</span><span class="token punctuation">:</span><span class="token string">"2023-07-23T14:22:39+08:00"</span><span class="token punctuation">,</span><span class="token string">"message"</span><span class="token punctuation">:</span><span class="token string">"log1输出error级别消息"</span><span class="token punctuation">&#125;</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>缺省logger和log1都只有error级别的输出，说明将glevel调整到error级别后，所有logger输出消息必须大于等于glevel。</p>
<p><strong>特别注意：zerolog.SetGlobalLevel()设置的是全局变量gLevel，它影响所有的Logger</strong></p>
<p>所以我们得出以下公式：</p>
<p>日志消息是否能够输出，应当满足下面的要求：<code>消息级别 &gt;= max(全局glevel,当前logger的level)</code></p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go">zerolog<span class="token punctuation">.</span><span class="token function">SetGlobalLevel</span><span class="token punctuation">(</span>zerolog<span class="token punctuation">.</span>Disabled<span class="token punctuation">)</span>
<span class="token comment">// zerolog.Disabled 为7，没有消息级别可以大于等于7，相当于禁用所有的Logger，自然不能够输出。</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>
<h5 id="上下文"><a href="#上下文" class="headerlink" title="上下文"></a><strong>上下文</strong></h5><p>zerolog是以Json对象格式输出的，还可以自定义一些键值对字段增加到上下文中以输出</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">package</span> main

<span class="token keyword">import</span> <span class="token punctuation">(</span>
	<span class="token string">"fmt"</span>
	<span class="token string">"github.com/rs/zerolog"</span>
	<span class="token string">"github.com/rs/zerolog/log"</span>
<span class="token punctuation">)</span>

<span class="token keyword">type</span> Person <span class="token keyword">struct</span> <span class="token punctuation">&#123;</span>
	Name <span class="token builtin">string</span> <span class="token string">`json:"name"`</span>
	Age  <span class="token builtin">int</span>    <span class="token string">`json:"age"`</span>
<span class="token punctuation">&#125;</span>

<span class="token keyword">func</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
	<span class="token keyword">var</span> all <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token punctuation">]</span>Person<span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span>
	<span class="token keyword">for</span> i <span class="token operator">:=</span> <span class="token number">0</span><span class="token punctuation">;</span> i <span class="token operator">&lt;</span> <span class="token number">10</span><span class="token punctuation">;</span> i<span class="token operator">++</span> <span class="token punctuation">&#123;</span>
		all <span class="token operator">=</span> <span class="token function">append</span><span class="token punctuation">(</span>all<span class="token punctuation">,</span> Person<span class="token punctuation">&#123;</span>Name<span class="token punctuation">:</span> fmt<span class="token punctuation">.</span><span class="token function">Sprintf</span><span class="token punctuation">(</span><span class="token string">"name%d"</span><span class="token punctuation">,</span> i<span class="token punctuation">)</span><span class="token punctuation">,</span> Age<span class="token punctuation">:</span> i <span class="token operator">+</span> <span class="token number">1</span><span class="token punctuation">&#125;</span><span class="token punctuation">)</span>
	<span class="token punctuation">&#125;</span>
	zerolog<span class="token punctuation">.</span><span class="token function">SetGlobalLevel</span><span class="token punctuation">(</span>zerolog<span class="token punctuation">.</span>InfoLevel<span class="token punctuation">)</span>
	log<span class="token punctuation">.</span><span class="token function">Info</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Bool</span><span class="token punctuation">(</span><span class="token string">"success"</span><span class="token punctuation">,</span> <span class="token boolean">true</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Str</span><span class="token punctuation">(</span><span class="token string">"Reason"</span><span class="token punctuation">,</span> <span class="token string">"File Not Found"</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Msg</span><span class="token punctuation">(</span><span class="token string">"文件没有找到"</span><span class="token punctuation">)</span>
	log<span class="token punctuation">.</span><span class="token function">Info</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Str</span><span class="token punctuation">(</span><span class="token string">"name"</span><span class="token punctuation">,</span> <span class="token string">"Tom"</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Floats32</span><span class="token punctuation">(</span><span class="token string">"Scores"</span><span class="token punctuation">,</span> <span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token builtin">float32</span><span class="token punctuation">&#123;</span><span class="token number">62.3</span><span class="token punctuation">,</span> <span class="token number">99.3</span><span class="token punctuation">,</span> <span class="token number">100</span><span class="token punctuation">&#125;</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Send</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
	fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"~~~~~~~~~~~~~~~~~~~~~~~~~~"</span><span class="token punctuation">)</span>
	log<span class="token punctuation">.</span><span class="token function">Info</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Any</span><span class="token punctuation">(</span><span class="token string">"data"</span><span class="token punctuation">,</span> all<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Send</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
	log<span class="token punctuation">.</span><span class="token function">Info</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Interface</span><span class="token punctuation">(</span><span class="token string">"data"</span><span class="token punctuation">,</span> all<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Msg</span><span class="token punctuation">(</span><span class="token string">"测试啊啊啊"</span><span class="token punctuation">)</span>

<span class="token punctuation">&#125;</span>

<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h5 id="错误日志"><a href="#错误日志" class="headerlink" title="错误日志"></a><strong>错误日志</strong></h5><pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">package</span> main

<span class="token keyword">import</span> <span class="token punctuation">(</span>
	<span class="token string">"errors"</span>
	<span class="token string">"github.com/rs/zerolog"</span>
	<span class="token string">"github.com/rs/zerolog/log"</span>
<span class="token punctuation">)</span>

<span class="token keyword">type</span> Person <span class="token keyword">struct</span> <span class="token punctuation">&#123;</span>
	Name <span class="token builtin">string</span> <span class="token string">`json:"name"`</span>
	Age  <span class="token builtin">int</span>    <span class="token string">`json:"age"`</span>
<span class="token punctuation">&#125;</span>

<span class="token keyword">func</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
	zerolog<span class="token punctuation">.</span>TimeFieldFormat <span class="token operator">=</span> zerolog<span class="token punctuation">.</span>TimeFormatUnix <span class="token comment">// 自定义time字段时间的格式，TimeFormatUnix时间戳</span>
	zerolog<span class="token punctuation">.</span>ErrorFieldName <span class="token operator">=</span> <span class="token string">"err"</span>                   <span class="token comment">// 修改日志Json中的缺省字段名error</span>

	<span class="token comment">// 错误日志</span>
	err <span class="token operator">:=</span> errors<span class="token punctuation">.</span><span class="token function">New</span><span class="token punctuation">(</span><span class="token string">"自定义错误"</span><span class="token punctuation">)</span>
	log<span class="token punctuation">.</span><span class="token function">Error</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Err</span><span class="token punctuation">(</span>err<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token comment">// err 字段，错误消息内容</span>
	<span class="token function">Send</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token comment">// 有错误消息了，message可以省略</span>
	<span class="token comment">//log.Fatal().Err(err).Send()</span>
	log<span class="token punctuation">.</span><span class="token function">Info</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Err</span><span class="token punctuation">(</span><span class="token boolean">nil</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Send</span><span class="token punctuation">(</span><span class="token punctuation">)</span>

<span class="token punctuation">&#125;</span>
<span class="token comment">// 输出</span>
<span class="token punctuation">&#123;</span><span class="token string">"level"</span><span class="token punctuation">:</span><span class="token string">"error"</span><span class="token punctuation">,</span><span class="token string">"err"</span><span class="token punctuation">:</span><span class="token string">"自定义错误"</span><span class="token punctuation">,</span><span class="token string">"time"</span><span class="token punctuation">:</span><span class="token number">1690095612</span><span class="token punctuation">&#125;</span>
<span class="token punctuation">&#123;</span><span class="token string">"level"</span><span class="token punctuation">:</span><span class="token string">"info"</span><span class="token punctuation">,</span><span class="token string">"time"</span><span class="token punctuation">:</span><span class="token number">1690095612</span><span class="token punctuation">&#125;</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h5 id="全局Logger"><a href="#全局Logger" class="headerlink" title="全局Logger"></a><strong>全局Logger</strong></h5><pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token comment">// 全局Logger定义如下</span>
<span class="token keyword">var</span> Logger <span class="token operator">=</span> zerolog<span class="token punctuation">.</span><span class="token function">New</span><span class="token punctuation">(</span>os<span class="token punctuation">.</span>Stderr<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">With</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Timestamp</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Logger</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>
<p>可以覆盖全局Logger</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go">log<span class="token punctuation">.</span>Logger <span class="token operator">=</span> log<span class="token punctuation">.</span><span class="token function">With</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Str</span><span class="token punctuation">(</span><span class="token string">"time"</span><span class="token punctuation">,</span> <span class="token string">"2020-01-02 15:04"</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Logger</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
log<span class="token punctuation">.</span><span class="token function">Info</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Send</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>


<h5 id="自定义Logger-1"><a href="#自定义Logger-1" class="headerlink" title="自定义Logger"></a><strong>自定义Logger</strong></h5><pre class="line-numbers language-go" data-language="go"><code class="language-go">	zerolog<span class="token punctuation">.</span>TimeFieldFormat <span class="token operator">=</span> <span class="token string">"2006-01-02 15:04:05"</span>
	logger <span class="token operator">:=</span> log<span class="token punctuation">.</span><span class="token function">With</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span>
		<span class="token function">Str</span><span class="token punctuation">(</span><span class="token string">"School"</span><span class="token punctuation">,</span> <span class="token string">"magedu"</span><span class="token punctuation">)</span><span class="token punctuation">.</span>
		<span class="token function">Caller</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span> <span class="token comment">// 增加日志调用的位置信息字段</span>
		<span class="token function">Logger</span><span class="token punctuation">(</span><span class="token punctuation">)</span>  <span class="token comment">// 返回logger</span>
	logger<span class="token punctuation">.</span><span class="token function">Info</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Send</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
	log<span class="token punctuation">.</span><span class="token function">Info</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Send</span><span class="token punctuation">(</span><span class="token punctuation">)</span>

<span class="token comment">// 输出</span>
<span class="token punctuation">&#123;</span><span class="token string">"level"</span><span class="token punctuation">:</span><span class="token string">"info"</span><span class="token punctuation">,</span><span class="token string">"School"</span><span class="token punctuation">:</span><span class="token string">"magedu"</span><span class="token punctuation">,</span><span class="token string">"time"</span><span class="token punctuation">:</span><span class="token string">"2023-07-23 15:05:23"</span><span class="token punctuation">,</span><span class="token string">"caller"</span><span class="token punctuation">:</span><span class="token string">"C:/Users/Administrator/GolandProjects/awesomeProject/hello.go:29"</span><span class="token punctuation">&#125;</span>
<span class="token punctuation">&#123;</span><span class="token string">"level"</span><span class="token punctuation">:</span><span class="token string">"info"</span><span class="token punctuation">,</span><span class="token string">"time"</span><span class="token punctuation">:</span><span class="token string">"2023-07-23 15:05:23"</span><span class="token punctuation">&#125;</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>


<pre class="line-numbers language-go" data-language="go"><code class="language-go">zerolog<span class="token punctuation">.</span>TimeFieldFormat <span class="token operator">=</span> <span class="token string">"2006-01-02 15:04:05"</span>
logger <span class="token operator">:=</span> zerolog<span class="token punctuation">.</span><span class="token function">New</span><span class="token punctuation">(</span>os<span class="token punctuation">.</span>Stderr<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">With</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Caller</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Logger</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Level</span><span class="token punctuation">(</span>zerolog<span class="token punctuation">.</span>InfoLevel<span class="token punctuation">)</span>
fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>logger<span class="token punctuation">.</span><span class="token function">GetLevel</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
logger<span class="token punctuation">.</span><span class="token function">Info</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Send</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
logger<span class="token punctuation">.</span><span class="token function">Error</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Send</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
log<span class="token punctuation">.</span><span class="token function">Info</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Send</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>




<h4 id="写日志文件-1"><a href="#写日志文件-1" class="headerlink" title="写日志文件"></a><strong>写日志文件</strong></h4><pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">package</span> main

<span class="token keyword">import</span> <span class="token punctuation">(</span>
	<span class="token string">"github.com/rs/zerolog"</span>
	<span class="token string">"github.com/rs/zerolog/log"</span>
	<span class="token string">"os"</span>
<span class="token punctuation">)</span>
<span class="token keyword">func</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
	zerolog<span class="token punctuation">.</span>TimeFieldFormat <span class="token operator">=</span> zerolog<span class="token punctuation">.</span>TimeFormatUnix <span class="token comment">// 自定义time字段时间的格式，TimeFormatUnix时间戳</span>
	zerolog<span class="token punctuation">.</span>ErrorFieldName <span class="token operator">=</span> <span class="token string">"err"</span>                   <span class="token comment">// 修改日志Json中的缺省字段名error</span>
	file<span class="token punctuation">,</span> err <span class="token operator">:=</span> os<span class="token punctuation">.</span><span class="token function">OpenFile</span><span class="token punctuation">(</span><span class="token string">"fuck.log"</span><span class="token punctuation">,</span> os<span class="token punctuation">.</span>O_CREATE<span class="token operator">|</span>os<span class="token punctuation">.</span>O_APPEND<span class="token operator">|</span>os<span class="token punctuation">.</span>O_WRONLY<span class="token punctuation">,</span> os<span class="token punctuation">.</span>ModePerm<span class="token punctuation">)</span>
	<span class="token keyword">if</span> err <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token punctuation">&#123;</span>
		log<span class="token punctuation">.</span><span class="token function">Fatal</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Err</span><span class="token punctuation">(</span>err<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Msg</span><span class="token punctuation">(</span><span class="token string">"open file error"</span><span class="token punctuation">)</span>
	<span class="token punctuation">&#125;</span>
	<span class="token keyword">defer</span> file<span class="token punctuation">.</span><span class="token function">Close</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
	levelwrite <span class="token operator">:=</span> zerolog<span class="token punctuation">.</span><span class="token function">MultiLevelWriter</span><span class="token punctuation">(</span>file<span class="token punctuation">,</span> os<span class="token punctuation">.</span>Stderr<span class="token punctuation">)</span>
	logger <span class="token operator">:=</span> zerolog<span class="token punctuation">.</span><span class="token function">New</span><span class="token punctuation">(</span>levelwrite<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">With</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Timestamp</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Logger</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
	logger<span class="token punctuation">.</span><span class="token function">Info</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Msg</span><span class="token punctuation">(</span><span class="token string">"日志写入到文件同时在控制台打印"</span><span class="token punctuation">)</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>如果只输出到文件可以使用<code>zerolog.New(f).With().Timestamp().Logger()</code></p>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="http://dycloudnavite.love">J.</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="http://dycloudnavite.love/2023/05/01/Golang%E6%97%A5%E5%BF%97%E7%AE%A1%E7%90%86/">http://dycloudnavite.love/2023/05/01/Golang%E6%97%A5%E5%BF%97%E7%AE%A1%E7%90%86/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="http://dycloudnavite.love" target="_blank">J.のblog</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/dujie5416/tags/%E4%BA%91%E5%8E%9F%E7%94%9F/">云原生</a><a class="post-meta__tags" href="/dujie5416/tags/golang/">golang</a></div><div class="post_share"><div class="addthis_inline_share_toolbox"></div><script src="//s7.addthis.com/js/300/addthis_widget.js#pubid=ra-5d034d84b42927bf" async="async"></script></div></div><div class="post-reward"><div class="reward-button"><i class="fas fa-qrcode"></i> 打赏</div><div class="reward-main"><ul class="reward-all"><li class="reward-item"><a href="/dujie5416/img/wechat.jpg" target="_blank"><img class="post-qr-code-img" src="/dujie5416/img/wechat.jpg" alt="微信"/></a><div class="post-qr-code-desc">微信</div></li><li class="reward-item"><a href="/dujie5416/img/alipay.jpg" target="_blank"><img class="post-qr-code-img" src="/dujie5416/img/alipay.jpg" alt="支付宝"/></a><div class="post-qr-code-desc">支付宝</div></li></ul></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/dujie5416/2023/05/03/Golang%E6%95%B0%E6%8D%AE%E5%BA%93%E6%A0%87%E5%87%86%E5%BC%80%E5%8F%91/"><img class="prev-cover" src="/dujie5416/img/golang.png" onerror="onerror=null;src='/dujie5416/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">Golang 数据库标准开发</div></div></a></div><div class="next-post pull-right"><a href="/dujie5416/2023/04/25/golang%E5%8C%85%E7%AE%A1%E7%90%86/"><img class="next-cover" src="/dujie5416/img/golang.png" onerror="onerror=null;src='/dujie5416/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">Golang包管理</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><div><a href="/dujie5416/2023/05/20/Channel%E9%80%9A%E9%81%93/" title="Channel通道"><img class="cover" src="/dujie5416/img/golang.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-05-20</div><div class="title">Channel通道</div></div></a></div><div><a href="/dujie5416/2023/05/06/Golang%E4%B8%AD%E7%9A%84GORM/" title="Golang GORM使用"><img class="cover" src="/dujie5416/img/golang.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-05-06</div><div class="title">Golang GORM使用</div></div></a></div><div><a href="/dujie5416/2023/06/23/Gin%E6%A1%86%E6%9E%B6/" title="Gin框架"><img class="cover" src="/dujie5416/img/golang.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-06-23</div><div class="title">Gin框架</div></div></a></div><div><a href="/dujie5416/2023/05/15/Golang%E5%8D%8F%E7%A8%8B/" title="Golang协程"><img class="cover" src="/dujie5416/img/golang.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-05-15</div><div class="title">Golang协程</div></div></a></div><div><a href="/dujie5416/2023/04/17/Golang%E5%8F%98%E9%87%8F%E9%80%83%E9%80%B8%E2%80%94%E2%80%94%E5%A0%86%E3%80%81%E6%A0%88/" title="Golang变量逃逸————堆、栈"><img class="cover" src="/dujie5416/img/golang.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-04-17</div><div class="title">Golang变量逃逸————堆、栈</div></div></a></div><div><a href="/dujie5416/2023/02/13/Golang%E5%AD%97%E7%AC%A6%E4%B8%B2string/" title="Golang字符串"><img class="cover" src="/dujie5416/img/golang.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-02-13</div><div class="title">Golang字符串</div></div></a></div></div></div><hr/><div id="post-comment"><div class="comment-head"><div class="comment-headline"><i class="fas fa-comments fa-fw"></i><span> 评论</span></div></div><div class="comment-wrap"><div><div id="lv-container" data-id="city" data-uid="MTAyMC81Njk5OS8zMzQ2Mw=="></div></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src="/dujie5416/img/touxiang.png" onerror="this.onerror=null;this.src='/dujie5416/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">J.</div><div class="author-info__description"></div></div><div class="card-info-data site-data is-center"><a href="/dujie5416/archives/"><div class="headline">文章</div><div class="length-num">73</div></a><a href="/dujie5416/tags/"><div class="headline">标签</div><div class="length-num">17</div></a><a href="/dujie5416/categories/"><div class="headline">分类</div><div class="length-num">11</div></a></div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#%E6%97%A5%E5%BF%97"><span class="toc-number">1.</span> <span class="toc-text">日志</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%A0%87%E5%87%86%E5%BA%93%E7%9A%84log%E5%8C%85"><span class="toc-number">1.0.1.</span> <span class="toc-text">标准库的log包</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#std%E4%BD%BF%E7%94%A8"><span class="toc-number">1.0.1.0.1.</span> <span class="toc-text">std使用</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#%E8%87%AA%E5%AE%9A%E4%B9%89Logger"><span class="toc-number">1.0.1.0.2.</span> <span class="toc-text">自定义Logger</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#%E5%86%99%E6%97%A5%E5%BF%97%E6%96%87%E4%BB%B6"><span class="toc-number">1.0.1.0.3.</span> <span class="toc-text">写日志文件</span></a></li></ol></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#ZeroLog"><span class="toc-number">1.0.2.</span> <span class="toc-text">ZeroLog</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#%E7%BC%BA%E7%9C%81Logger"><span class="toc-number">1.0.2.0.1.</span> <span class="toc-text">缺省Logger</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#%E7%BA%A7%E5%88%AB"><span class="toc-number">1.0.2.0.2.</span> <span class="toc-text">级别</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#%E4%B8%8A%E4%B8%8B%E6%96%87"><span class="toc-number">1.0.2.0.3.</span> <span class="toc-text">上下文</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#%E9%94%99%E8%AF%AF%E6%97%A5%E5%BF%97"><span class="toc-number">1.0.2.0.4.</span> <span class="toc-text">错误日志</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#%E5%85%A8%E5%B1%80Logger"><span class="toc-number">1.0.2.0.5.</span> <span class="toc-text">全局Logger</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#%E8%87%AA%E5%AE%9A%E4%B9%89Logger-1"><span class="toc-number">1.0.2.0.6.</span> <span class="toc-text">自定义Logger</span></a></li></ol></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%86%99%E6%97%A5%E5%BF%97%E6%96%87%E4%BB%B6-1"><span class="toc-number">1.0.2.1.</span> <span class="toc-text">写日志文件</span></a></li></ol></li></ol></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/dujie5416/2023/07/29/%E6%A0%B9%E6%8D%AErouter%E6%98%BE%E7%A4%BA%E5%B7%A6%E4%BE%A7%E8%8F%9C%E5%8D%95%E6%A0%8F%E9%9A%90%E8%97%8F%E6%9F%90%E4%B8%AA%E8%8F%9C%E5%8D%95%E9%80%89%E9%A1%B9/" title="vue3左侧菜单隐藏某选项"><img src="/dujie5416/img/golang.png" onerror="this.onerror=null;this.src='/dujie5416/img/404.jpg'" alt="vue3左侧菜单隐藏某选项"/></a><div class="content"><a class="title" href="/dujie5416/2023/07/29/%E6%A0%B9%E6%8D%AErouter%E6%98%BE%E7%A4%BA%E5%B7%A6%E4%BE%A7%E8%8F%9C%E5%8D%95%E6%A0%8F%E9%9A%90%E8%97%8F%E6%9F%90%E4%B8%AA%E8%8F%9C%E5%8D%95%E9%80%89%E9%A1%B9/" title="vue3左侧菜单隐藏某选项">vue3左侧菜单隐藏某选项</a><time datetime="2023-07-29T06:32:00.000Z" title="发表于 2023-07-29 14:32:00">2023-07-29</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/dujie5416/2023/07/13/Vue%E7%8A%B6%E6%80%81%E7%AE%A1%E7%90%86/" title="Vue状态管理"><img src="/dujie5416/img/golang.png" onerror="this.onerror=null;this.src='/dujie5416/img/404.jpg'" alt="Vue状态管理"/></a><div class="content"><a class="title" href="/dujie5416/2023/07/13/Vue%E7%8A%B6%E6%80%81%E7%AE%A1%E7%90%86/" title="Vue状态管理">Vue状态管理</a><time datetime="2023-07-13T09:29:00.000Z" title="发表于 2023-07-13 17:29:00">2023-07-13</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/dujie5416/2023/06/27/%E5%9F%BA%E4%BA%8EIOC%E8%A7%A3%E5%86%B3%E5%AF%B9%E8%B1%A1%E4%BE%9D%E8%B5%96%E9%97%AE%E9%A2%98/" title="基于IOC解决对象依赖问题"><img src="/dujie5416/img/golang.png" onerror="this.onerror=null;this.src='/dujie5416/img/404.jpg'" alt="基于IOC解决对象依赖问题"/></a><div class="content"><a class="title" href="/dujie5416/2023/06/27/%E5%9F%BA%E4%BA%8EIOC%E8%A7%A3%E5%86%B3%E5%AF%B9%E8%B1%A1%E4%BE%9D%E8%B5%96%E9%97%AE%E9%A2%98/" title="基于IOC解决对象依赖问题">基于IOC解决对象依赖问题</a><time datetime="2023-06-27T03:32:00.000Z" title="发表于 2023-06-27 11:32:00">2023-06-27</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/dujie5416/2023/06/23/Gin%E6%A1%86%E6%9E%B6/" title="Gin框架"><img src="/dujie5416/img/golang.png" onerror="this.onerror=null;this.src='/dujie5416/img/404.jpg'" alt="Gin框架"/></a><div class="content"><a class="title" href="/dujie5416/2023/06/23/Gin%E6%A1%86%E6%9E%B6/" title="Gin框架">Gin框架</a><time datetime="2023-06-23T06:32:00.000Z" title="发表于 2023-06-23 14:32:00">2023-06-23</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/dujie5416/2023/06/04/ServeMux%E3%80%81httprouter/" title="ServeMux、httprouter"><img src="/dujie5416/img/golang.png" onerror="this.onerror=null;this.src='/dujie5416/img/404.jpg'" alt="ServeMux、httprouter"/></a><div class="content"><a class="title" href="/dujie5416/2023/06/04/ServeMux%E3%80%81httprouter/" title="ServeMux、httprouter">ServeMux、httprouter</a><time datetime="2023-06-04T03:32:00.000Z" title="发表于 2023-06-04 11:32:00">2023-06-04</time></div></div></div></div></div></div></main><footer id="footer" style="background-image: url('/dujie5416/img/longzhu.png')"><div id="footer-wrap"><div class="copyright">&copy;2019 - 2024  <i id="heartbeat" class="fa fas fa-heartbeat"></i> J.</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a><a href="http://beian.miit.gov.cn/"  style="color:#f72b07" target="_blank">京ICP备2022023567号</a></div></div><link rel="stylesheet" href="https://fastly.jsdelivr.net/gh/HCLonely/images@master/others/heartbeat.min.css"></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="translateLink" type="button" title="简繁转换">繁</button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><a id="to_comment" href="#post-comment" title="直达评论"><i class="fas fa-comments"></i></a><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="algolia-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">搜索</span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="search-wrap"><div id="algolia-search-input"></div><hr/><div id="algolia-search-results"><div id="algolia-hits"></div><div id="algolia-pagination"></div><div id="algolia-info"><div class="algolia-stats"></div><div class="algolia-poweredBy"></div></div></div></div></div><div id="search-mask"></div></div><div id="rightMenu"><div class="rightMenu-group rightMenu-small"><div class="rightMenu-item" id="menu-backward"><i class="fa-solid fa-arrow-left"></i></div><div class="rightMenu-item" id="menu-forward"><i class="fa-solid fa-arrow-right"></i></div><div class="rightMenu-item" id="menu-refresh"><i class="fa-solid fa-arrow-rotate-right"></i></div><div class="rightMenu-item" id="menu-home"><i class="fa-solid fa-house"></i></div></div><div class="rightMenu-group rightMenu-line rightMenuOther"><a class="rightMenu-item menu-link" href="/archives/"><i class="fa-solid fa-archive"></i><span>文章归档</span></a><a class="rightMenu-item menu-link" href="/categories/"><i class="fa-solid fa-folder-open"></i><span>文章分类</span></a><a class="rightMenu-item menu-link" href="/tags/"><i class="fa-solid fa-tags"></i><span>文章标签</span></a></div><div class="rightMenu-group rightMenu-line rightMenuNormal"><a class="rightMenu-item menu-link" id="menu-radompage" href="/random/index.html"><i class="fa-solid fa-shoe-prints"></i><span>随便逛逛</span></a><div class="rightMenu-item" id="menu-translate"><i class="fa-solid fa-earth-asia"></i><span>繁简切换</span></div><div class="rightMenu-item" id="menu-darkmode"><i class="fa-solid fa-moon"></i><span>切换模式</span></div></div></div><div id="rightmenu-mask"></div><div><script src="/dujie5416/js/utils.js"></script><script src="/dujie5416/js/main.js"></script><script src="/dujie5416/js/tw_cn.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.umd.min.js"></script><script src="https://cdn.jsdelivr.net/npm/algoliasearch/dist/algoliasearch-lite.umd.min.js"></script><script src="https://cdn.jsdelivr.net/npm/instantsearch.js/dist/instantsearch.production.min.js"></script><script src="/dujie5416/js/search/algolia.js"></script><script>var preloader = {
  endLoading: () => {
    document.body.style.overflow = 'auto';
    document.getElementById('loading-box').classList.add("loaded")
  },
  initLoading: () => {
    document.body.style.overflow = '';
    document.getElementById('loading-box').classList.remove("loaded")

  }
}
window.addEventListener('load',preloader.endLoading())</script><div class="js-pjax"><script>function loadLivere () {
  if (typeof LivereTower === 'object') {
    window.LivereTower.init()
  }
  else {
    (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
    })(document, 'script');
  }
}

if ('Livere' === 'Livere' || !false) {
  if (false) btf.loadComment(document.getElementById('lv-container'), loadLivere)
  else loadLivere()
}
else {
  function loadOtherComment () {
    loadLivere()
  }
}</script></div><script defer src="https://npm.elemecdn.com/jquery@latest/dist/jquery.min.js"></script><script data-pjax defer src="https://npm.elemecdn.com/tzy-blog/lib/js/theme/chocolate.js"></script><canvas id="universe"></canvas><script defer src="/js/universe.js"></script><script defer data-pjax src="/js/rightMenu.js"></script><div class="aplayer no-destroy" data-id="7427714271" data-server="netease" data-type="playlist" data-fixed="true" data-mini="true" data-listFolded="false" data-order="random" data-lrctype="1" data-preload="none" data-autoplay="true" muted></div><script id="click-show-text" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/click-show-text.min.js" data-mobile="false" data-text="I,LOVE,YOU" data-fontsize="15px" data-random="false" async="async"></script><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.js"></script><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/metingjs/dist/Meting.min.js"></script><script src="https://cdn.jsdelivr.net/npm/pjax/pjax.min.js"></script><script>let pjaxSelectors = ["meta[property=\"og:image\"]","meta[property=\"og:title\"]","meta[property=\"og:url\"]","head > title","#config-diff","#body-wrap","#rightside-config-hide","#rightside-config-show",".js-pjax"]

var pjax = new Pjax({
  elements: 'a:not([target="_blank"])',
  selectors: pjaxSelectors,
  cacheBust: false,
  analytics: false,
  scrollRestoration: false
})

document.addEventListener('pjax:send', function () {

  // removeEventListener scroll 
  window.tocScrollFn && window.removeEventListener('scroll', window.tocScrollFn)
  window.scrollCollect && window.removeEventListener('scroll', scrollCollect)

  typeof preloader === 'object' && preloader.initLoading()
  document.getElementById('rightside').style.cssText = "opacity: ''; transform: ''"
  
  if (window.aplayers) {
    for (let i = 0; i < window.aplayers.length; i++) {
      if (!window.aplayers[i].options.fixed) {
        window.aplayers[i].destroy()
      }
    }
  }

  typeof typed === 'object' && typed.destroy()

  //reset readmode
  const $bodyClassList = document.body.classList
  $bodyClassList.contains('read-mode') && $bodyClassList.remove('read-mode')

  typeof disqusjs === 'object' && disqusjs.destroy()
})

document.addEventListener('pjax:complete', function () {
  window.refreshFn()

  document.querySelectorAll('script[data-pjax]').forEach(item => {
    const newScript = document.createElement('script')
    const content = item.text || item.textContent || item.innerHTML || ""
    Array.from(item.attributes).forEach(attr => newScript.setAttribute(attr.name, attr.value))
    newScript.appendChild(document.createTextNode(content))
    item.parentNode.replaceChild(newScript, item)
  })

  GLOBAL_CONFIG.islazyload && window.lazyLoadInstance.update()

  typeof chatBtnFn === 'function' && chatBtnFn()
  typeof panguInit === 'function' && panguInit()

  // google analytics
  typeof gtag === 'function' && gtag('config', '', {'page_path': window.location.pathname});

  // baidu analytics
  typeof _hmt === 'object' && _hmt.push(['_trackPageview',window.location.pathname]);

  typeof loadMeting === 'function' && document.getElementsByClassName('aplayer').length && loadMeting()

  // prismjs
  typeof Prism === 'object' && Prism.highlightAll()

  typeof preloader === 'object' && preloader.endLoading()
})

document.addEventListener('pjax:error', (e) => {
  if (e.request.status === 404) {
    pjax.loadUrl('/404.html')
  }
})</script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div><!-- hexo injector body_end start --><script data-pjax>
  function butterfly_clock_anzhiyu_injector_config(){
    var parent_div_git = document.getElementsByClassName('sticky_layout')[0];
    var item_html = '<div class="card-widget card-clock"><div class="card-glass"><div class="card-background"><div class="card-content"><div id="hexo_electric_clock"><img class="entered loading" id="card-clock-loading" src="https://cdn.cbd.int/hexo-butterfly-clock-anzhiyu/lib/loading.gif" style="height: 120px; width: 100%;" data-ll-status="loading"/></div></div></div></div></div>';
    console.log('已挂载butterfly_clock_anzhiyu')
    if(parent_div_git) {
      parent_div_git.insertAdjacentHTML("afterbegin",item_html)
    }
  }
  var elist = 'null'.split(',');
  var cpage = location.pathname;
  var epage = 'all';
  var qweather_key = '56289903f0d448dfbe8262dba0175f70';
  var gaud_map_key = '01603f2b2d08d0e947bb101e9d9b148b';
  var baidu_ak_key = 'undefined';
  var flag = 0;
  var clock_rectangle = '112.982279,28.19409';
  var clock_default_rectangle_enable = 'false';

  for (var i=0;i<elist.length;i++){
    if (cpage.includes(elist[i])){
      flag++;
    }
  }

  if ((epage ==='all')&&(flag == 0)){
    butterfly_clock_anzhiyu_injector_config();
  }
  else if (epage === cpage){
    butterfly_clock_anzhiyu_injector_config();
  }
  </script><script src="https://widget.qweather.net/simple/static/js/he-simple-common.js?v=2.0"></script><script data-pjax src="https://cdn.cbd.int/hexo-butterfly-clock-anzhiyu/lib/clock.min.js"></script><!-- hexo injector body_end end --><script src="/dujie5416/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"tagMode":false,"debug":false,"model":{"jsonPath":"/dujie5416/live2dw/assets/tororo.model.json"},"display":{"position":"right","width":150,"height":350,"hOffset":20,"vOffset":-20},"mobile":{"show":false},"log":false,"pluginJsPath":"lib/","pluginModelPath":"assets/","pluginRootPath":"live2dw/"});</script><script async>window.onload=function(){var a=document.createElement('script'),b=document.getElementsByTagName('script')[0];a.type='text/javascript',a.async=!0,a.src='/sw-register.js?v='+Date.now(),b.parentNode.insertBefore(a,b)};</script></body></html>